package com.jielihaofeng.atguigu.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @author Johnnie Wind
 * @description NIO 服务端
 * @date 2021/11/25 15:42
 */
public class NIOServer {
    public static void main(String[] args) throws IOException {
        // 服务端
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);

        // 获取Selector对象
        Selector selector = Selector.open();
        // 注册并监听OP_ACCEPT事件
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // 注册后的 selectionKey 数量
        System.out.println("注册后的 selectionKey 数量" + selector.keys().size());

        while (true) {

//            selector.select();
            if (selector.select(1000) == 0) {
                System.out.println("服务端等待了1秒，无连接");
                continue;
            }

            // 获取selectionKey的迭代器
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            System.out.println("selectedKeys 数量=" + selector.selectedKeys().size());

            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                // 根据key上的事件做不同处理
                if (key.isAcceptable()) {
                    // 获取客户端的 socketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功 生成了一个socketChannel " + socketChannel.hashCode());
                    // 将客户的设置成非阻塞的
                    socketChannel.configureBlocking(false);
                    // 将当前的 socketChannel 注册到 selector，关注事件为 OP_READ，同时给socketChannel关联一个Buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    // 客户端连接后注册的 selectionKey 数量
                    System.out.println("客户端连接后注册的 selectionKey 数量" + selector.keys().size());
                }
                if (key.isReadable()) {
                    // 通过key反向获取 SocketChannel
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    System.out.println("from 客户端 " + new String(buffer.array()));
                }

                // 移除，防止重复调用
                iterator.remove();
            }
        }
    }
}
